import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { Alert, message, Tabs, Form } from 'antd';
import React, { useEffect, useState } from 'react';
import { FormattedMessage, history, SelectLang, useIntl, useModel } from 'umi';
import styles from './index.less';
import { createImgMsg, login, getCurrentUserMenu } from '@/services/api/user';
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [form] = Form.useForm();
  const [imgData, setimgData] = useState({
    png: '',
    verificationcode: '',
  });
  const intl = useIntl();
  useEffect(() => {
    getImg();
  }, []);
  useEffect(() => {
    console.log()
  }, [])
  const getImg = () => {
    createImgMsg().then((res) => {
      setimgData(res?.data);
    });
  };
  const fetchUserInfo = async (userInfo: any) => {
    if (userInfo) {

      await new Promise<void>((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, 300);
      })
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
        userMenusKeys: [],
        accessData: []
      }));

    }
  };

  const handleSubmit = async (values: any) => {
    try {
      console.log(values);
      // 登录
      const msg: any = await login({
        ...values,
        ...{
          loginParamType: '1',
        },
      });
      if (msg.meta.code === 200) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);

        await fetchUserInfo(msg.data);
        /** 此方法会跳转到 redirect 参数所在的位置 */
        history.push('/basicManage');
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
      getImg();
    } catch (error) {
      // const defaultLoginFailureMessage = intl.formatMessage({
      //   id: 'pages.login.failure',
      //   defaultMessage: '登录失败，请重试！',
      // });
      // message.error(defaultLoginFailureMessage);
      getImg();
      form.setFieldsValue({
        ['kaptcha']: '',
      });
    }
  };
  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <div style={{ margin: '20px', textAlign: 'center', fontSize: '30px', fontWeight: 'bold' }}>
          中化信息管理平台
        </div>

        <LoginForm
          form={form}
          // logo={<img alt="logo" src="/logo.svg" />}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <ProFormText
            name="account"
            fieldProps={{
              size: 'large',
              prefix: <UserOutlined className={styles.prefixIcon} />,
            }}
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          />
          <ProFormText.Password
            name="passwd"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined className={styles.prefixIcon} />,
            }}
            rules={[
              {
                required: true,
                message: '请输入密码！',
              },
            ]}
          />
          <div className={styles.kaptchaWrap}>
            <div className={styles.kaptcha}>
              <ProFormText
                name="kaptcha"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                allowClear
                rules={[
                  {
                    required: true,
                    message: '请输入验证码!',
                  },
                ]}
              />
            </div>
            <div className={styles.verfucationcode} onClick={getImg}>
              <img className={styles.png} src={imgData.png} alt="" />
            </div>
          </div>
        </LoginForm>
      </div>
      {/* <Footer /> */}
    </div>
  );
};

export default Login;
